package com.whiteape.book.core.parser;

import com.whiteape.book.core.manager.ParserManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceMediaInfoBean;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.URLUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Single;

public class MediaInfoParser {
//    public static Single<CollectionMediaBean> parse(CollectionMediaBean collectionMediaBean, String html) {
//        return parse(collectionMediaBean.getSiteSourceBean(), collectionMediaBean.getId(), collectionMediaBean.getVarMap(), html);
//    }
    /**
     * 处理书籍详情，获取书籍的基本信息，以及章节列表的链接地址
     * @param html
     * @return
     */
    public static Single<CollectionMediaBean> parse(CollectionMediaBean collectionMediaBean, String html) {
        collectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        SiteSourceBean siteSourceBean = collectionMediaBean.getSiteSourceBean();
        String currentUrl = collectionMediaBean.getId();
        HashMap<String, String> varMap = collectionMediaBean.getVarMap();

        if (siteSourceBean == null || StringUtils.isEmpty(html)) {
            return Single.create(emitter -> emitter.onError(new Throwable("MediaInfoParser.parse check args error")));
        }

        return Single.create(emitter -> {

            CollectionMediaBean bookBean = parseDirectly(siteSourceBean, currentUrl, varMap, html);
            if (StringUtils.isEmpty(bookBean.getTitle())) {
                bookBean.setTitle(collectionMediaBean.getTitle());
            }
            if (StringUtils.isEmpty(bookBean.getCoverUrl())) {
                bookBean.setCoverUrl(collectionMediaBean.getCoverUrl());
            }
            if (StringUtils.isEmpty(bookBean.getAuthor())) {
                bookBean.setAuthor(collectionMediaBean.getAuthor());
            }
            if (StringUtils.isEmpty(bookBean.getDesc())) {
                bookBean.setDesc(collectionMediaBean.getDesc());
            }
            if (StringUtils.isEmpty(bookBean.getLastChapter())) {
                bookBean.setLastChapter(collectionMediaBean.getLastChapter());
            }
            if (StringUtils.isEmpty(bookBean.getLastUpdated())) {
                bookBean.setLastUpdated(collectionMediaBean.getLastUpdated());
            }
            if (StringUtils.isEmpty(bookBean.getState())) {
                bookBean.setState(collectionMediaBean.getState());
            }
            emitter.onSuccess(bookBean);
//            emitter.onComplete();

        });
    }

    public static CollectionMediaBean parseDirectly(SiteSourceBean siteSourceBean, String currentUrl, HashMap<String, String> varMap, String html) {
        return parseDirectly(siteSourceBean, currentUrl, varMap, html, true);

    }

    public static CollectionMediaBean parseDirectly(SiteSourceBean siteSourceBean, String currentUrl, HashMap<String, String> varMap, String html, boolean parseCatalog) {

        CollectionMediaBean bookBean = new CollectionMediaBean();
        bookBean.setVarMap(varMap);
        bookBean.setMediaType(siteSourceBean.getSiteType());
        bookBean.setId(currentUrl);
        bookBean.setSiteSourceBean(siteSourceBean);
        SiteSourceMediaInfoBean ruleBean = siteSourceBean.getMediaInfoDetailRule();

//        Document doc = Jsoup.parse(html);
//        Element body = doc.body();

        bookBean.setAuthor(ParserManager.parseOne(currentUrl, html, ruleBean.getAuthor(), varMap));
        bookBean.setCategory(ParserManager.parseOne(currentUrl, html, ruleBean.getCategory(), varMap));
        String coverUrl = ParserManager.parseOne(currentUrl, html, ruleBean.getCoverUrl(),varMap);
        //转化为绝对路径
        if (!StringUtils.isEmpty(coverUrl) && !coverUrl.startsWith("http")) {
            coverUrl = URLUtils.getAbsolutePath(currentUrl, coverUrl);
        }

        bookBean.setCoverUrl(coverUrl);

        bookBean.setDesc(ParserManager.parseOne(currentUrl, html, ruleBean.getDesc(), varMap));
        bookBean.setLastChapter(ParserManager.parseOne(currentUrl, html, ruleBean.getLastChapter(), varMap));
        bookBean.setLastUpdated(ParserManager.parseOne(currentUrl, html, ruleBean.getLastUpdated(), varMap));
        bookBean.setState(ParserManager.parseOne(currentUrl, html, ruleBean.getState(),varMap));
        bookBean.setTitle(ParserManager.parseOne(currentUrl, html, ruleBean.getTitle(),varMap));
        bookBean.setWordCount(ParserManager.parseOne(currentUrl, html, ruleBean.getWordCount(),varMap));

        String chapterListUrl = ParserManager.parseOne(currentUrl, html, ruleBean.getCatalogUrl(),varMap);
        //转化为绝对路径
        if (!chapterListUrl.startsWith("http")) {
            //如果是""，那么转化后，就变成currentUrl也就是书籍详情页的url了
            chapterListUrl = URLUtils.getAbsolutePath(currentUrl, chapterListUrl);
        }
        bookBean.setCatalogUrl(chapterListUrl);
        if (parseCatalog && URLUtils.isUrlsEqual(currentUrl, chapterListUrl)) {
            //如果当前详情url和目录url一样，那么，直接把目录解析出来
            List<MediaChapterBean> chapters = CatalogParser.parseDirectly(siteSourceBean, bookBean, html);
            bookBean.setMediaChapterList(chapters);
        }
        //TODO 下一章的规则是一条，但是结果会有多条，多个下一页
        bookBean.setCatalogNextPageUrl(ParserManager.parseOne(currentUrl, html, ruleBean.getCatalogNextPageUrl(), varMap));

        return bookBean;

    }

}
